package org.halk.servie.impl;

import org.halk.config.AsyncConfiguration;
import org.halk.repository.UserTestRepository;
import org.halk.servie.UserTestService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

/**
 * 多线程与事务的结合，线程内无法实现事务回滚，（目前）
 * 可以将不涉及到更新的操作放入线程内执行，
 * 将计算结果返回至外部执行（受事务管理）
 * @Author halk
 * @Date 2024/3/11 15:31
 **/
@Service
public class UserTestServiceImpl implements UserTestService {

    @Resource
    private AsyncConfiguration asyncConfiguration;

    @Resource
    private UserTestRepository userTestRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateId(String id) throws ExecutionException, InterruptedException {
        userTestRepository.updateName(id, "xxp1");
        Executor executor = asyncConfiguration.getAsyncExecutor();

        ArrayList<CompletableFuture<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            CompletableFuture<Integer> resultFuture = CompletableFuture.supplyAsync(() -> extracted(finalI), executor);
            futures.add(resultFuture);
        }

        //等待所有线程执行完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).get();

        //对每个线程的计算结果进行处理
        for (CompletableFuture<Integer> future : futures) {
            Integer i = future.get();
            System.out.println(i);
        }

        System.out.println(1);
    }

    public Integer extracted(Integer i) {
        if (i == 2) {
//            int ii = 1 / 0;
        }
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return i;
    }
}
